<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item
              label="客户名称"
              :label-col-flex="pageData.labelColFlex"
              field="customerName"
            >
              <a-select
                popup-container="html"
                class="bacClass"
                v-model="pageData.customerName"
                allow-clear
                allow-search
                @search="seatchHandler($event, 1)"
                @focus="selectAwait(1)"
              >
                <a-option
                  v-for="item in pageData.customerList"
                  :key="item.id"
                  :value="item.brandName"
                  >{{ item.brandName }}</a-option
                >
              </a-select>
            </a-form-item>
            <a-form-item
              :style="{ width: '325px' }"
              label-col-flex="100px"
              label="设备机型"
              field="machineTypeName"
            >
              <a-select
                popup-container="html"
                :class="{ bacClass: true }"
                v-model="pageData.machineTypeName"
                @search="searchMachineTypeList"
                :filter-option="false"
                allow-search
                allow-clear
                @focus="focusMachineTypeList"
              >
                <a-option v-for="item in pageData.machineTypeList" :value="item.typeName">
                  {{ item.typeName }}
                </a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="日期">
              <a-range-picker
                popup-container="html"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                class="bacClass"
                @change="pickerChange"
                style="width: 254px"
                v-model="pageData.storeTime"
              />
            </a-form-item>
          </a-form>
        </div>
        <div class="my-tool-bar">
          <Toolbar
            :items="pageData.btnList"
            @select="selectHander"
            @add="addHandler"
            @del="deleteHandler"
            @export="exportHandler"
            @import="importHandler"
            @excel="downloadHandler"
          >
          </Toolbar>
        </div>
      </div>

      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
    </template>
    <template #pageTabel>
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        :suppressDragLeaveHidesColumns="true"
        @grid-ready="gridReady"
        style="height: calc(100% - 45px)"
        @columnResized="onColumnResized"
        @columnMoved="onColumnMoved"
        @columnVisible="onColumnVisible"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="tableDataList"
        :columnDefs="vehicleColDefs"
        :localeText="localeText1"
        rowSelection="multiple"
      ></AgGridVuesCopys>
      <paginationCopys
        :page-size-options="pagingList1"
        :total="pageData.total"
        show-total
        show-jumper
        @change="PageSize"
        @page-size-change="change1"
        style="justify-content: center"
        :page-size="pageData.size"
        :current="pageData.page"
      />
    </template>
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :height="'90%'"
      popup-container=".arco-tabs-content"
      unmount-on-close
      :ok-loading="pageData.pageLoading"
      :visible="pageData.AddDrawer"
      @ok="sideOk"
      @cancel="pageData.AddDrawer = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form size="small" :model="dataForm" layout="inline">
          <a-form-item
            :style="{ width: '325px' }"
            label-col-flex="100px"
            label="客户名称"
            :label-col-flex="dataForm.labelColFlex"
            field="customerName"
          >
            <a-select
              popup-container="html"
              class="bacClass"
              v-model="dataForm.customerName"
              allow-clear
              allow-search
              @search="seatchHandler($event, 2)"
              @focus="selectAwait(2)"
              :disabled="disableOr"
            >
              <a-option
                v-for="item in dataForm.customerList"
                :key="item.id"
                :value="item.typeName"
                >{{ item.typeName }}</a-option
              >
            </a-select>
          </a-form-item>
          <a-form-item
            :style="{ width: '325px' }"
            label-col-flex="100px"
            label="设备机型"
            field="machineTypeName"
          >
            <a-select
              popup-container="html"
              :class="{ bacClass: true }"
              v-model="dataForm.machineTypeName"
              @search="searchMachineTypeList"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusMachineTypeList"
              :disabled="disableOr"
            >
              <a-option v-for="item in pageData.machineTypeList" :value="item.typeName">
                {{ item.typeName }}
              </a-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :style="{ width: '325px' }"
            label-col-flex="100px"
            label="织单类型"
            field="weaveOrderTypeName"
          >
            <a-select
              popup-container="html"
              :class="{ bacClass: true }"
              v-model="dataForm.weaveOrderTypeName"
              @search="searchweaveOrderTypeList"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusWeaveOrderTypeList"
              :disabled="disableOr"
            >
              <a-option v-for="item in dataForm.weaveOrderTypelist" :value="item.typeName">
                {{ item.typeName }}
              </a-option>
            </a-select>
          </a-form-item>

          <!-- 限制只能输入整数 -->
          <a-form-item label="公斤/匹" field="standardCroppingWeight" :style="{ width: '325px' }">
            <a-input-number
              class="bacClass"
              :min="0"
              :step="1"
              :precision="0"
              v-model="dataForm.standardCroppingWeight"
            />
          </a-form-item>
          <a-form-item label="开始重量" field="minWeight" :style="{ width: '325px' }">
            <a-input-number class="bacClass" :min="0" v-model="dataForm.minWeight" :precision="2" />
          </a-form-item>
          <a-form-item label="结束重量" field="maxWeight" :style="{ width: '325px' }">
            <a-input-number class="bacClass" :min="0" v-model="dataForm.maxWeight" :precision="2" />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script setup lang="ts">
  import { reactive, ref, onMounted } from 'vue'
  import { post } from '@/api/http'
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import Toolbar from '@/components/Toolbar.vue'
  import usePermission from '@/store/modules/permission'
  import { Message, Modal } from '@arco-design/web-vue'
  import { dysuff } from '@/api/laboratory/index'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'
  import { orderFn } from '@/api/laboratory/other'
  import filedownload from 'js-file-download'
  import AddOrEditDrawer from '@/views/FinishedWarehouseManagement/components/FinishedProductOutstock/components/AddOrEditDrawer.vue'
  import { useTable } from '@/hooks/table'
  import { assTable } from '@/utils/assemblyLevelTable'
  import axios from 'axios'
  import { baseURL } from '../../../api/axios.config'

  const dataForm = reactive<any>({
    customerName: '',
    machineTypeName: '',
    weaveOrderTypeName: '',
    standardCroppingWeight: '', //公斤/匹
    minWeight: '',
    maxWeight: '',
    weaveOrderTypelist: [],
    id: '',
  })
  const pageData = reactive<any>({
    storeTime: null,
    customerName: '',
    machineTypeName: '',
    weaveOrderTypeName: '',
    btnList: [],
    total: 0,
    current: 1,
    size: 10,
    page: 1,
    tapShow: false,
    AddDrawer: false,
    sideTitle: '新增重量限制表',
    pageLoading: false,
  })
  const headerShow = ref(true)

  const pickerChange = (dateString: any, value: any) => {
    if (dateString) {
      pageData.beginTime = dateString[0]
      pageData.endTime = dateString[1]
    } else {
      pageData.beginTime = ''
      pageData.endTime = ''
    }
  }
  const seatchHandler = async (value: any, index: number) => {
    if (value) {
      loading.value = true
      await selectAwait(index, value, (data: any) => {
        console.log(index)
        console.log(value)
        console.log(data)

        options.value = data
      })

      loading.value = false
    } else {
      options.value = []
    }
  }

  //设备机型下拉
  const loading = ref(false)
  const options: any = ref([])

  const searchMachineTypeList = (value: any) => {
    if (value) {
      loading.value = true
      jitaileixing(value)
      options.value = pageData.machineTypeList
      loading.value = false
    } else {
      options.value = []
    }
  }

  const searchweaveOrderTypeList = (value: any) => {
    if (value) {
      loading.value = true
      zhidanleixing(value)
      options.value = dataForm.weaveOrderTypeName
      loading.value = false
    } else {
      options.value = []
    }
  }
  const localeText1: any = ref(localeText)
  const pagingList1: any = ref(pagingList)
  const jitaileixing = (ob: any) => {
    if (ob == null || ob == undefined) {
      ob = ''
    }
    post({
      url: 'planSingle/machineType/getFieldValue',
      data: {
        typeName: ob,
      },
    }).then((res: any) => {
      if (res.code == 200) {
        //pageData.machineTypeList = res.data
        pageData.machineTypeList = []
        res.data.map((o: any) => {
          pageData.machineTypeList.push({ typeName: o.typeName })
        })

        pageData.machineTypeList = Array.from(new Set(pageData.machineTypeList))
      }
    })
  }
  // 机型下拉框
  const focusMachineTypeList = () => {
    jitaileixing('')
  }

  //织单类型

  const zhidanleixing = (ob: any) => {
    console.log(ob)

    if (ob == null || ob == undefined) {
      ob = ''
    }
    post({
      url: 'planSingle/weaveOrderType/getListGroupBy ',
      data: {},
    }).then((res: any) => {
      if (res.code == 200) {
        console.log(res)

        //pageData.weaveOrderTypelist = res.data
        dataForm.weaveOrderTypelist = []

        res.data.map((o: any) => {
          dataForm.weaveOrderTypelist.push({ typeName: o.weaveOrderType })
        })
        console.log(dataForm.weaveOrderTypelist)

        // dataForm.weaveOrderTypelist = Array.from(new Set(dataForm.weaveOrderTypelist))
      }
    })
  }
  // 织单类型下拉框
  const focusWeaveOrderTypeList = () => {
    zhidanleixing('')
  }

  const clear = () => {
    dataForm.weaveOrderType = ''
    dataForm.weaveOrderTypeName = []
    dataForm.machineTypeList = []
    dataForm.minWeight = ''
    dataForm.maxWeight = ''
    dataForm.standardCroppingWeight = ''
    dataForm.weaveOrderTypeName = ''
    dataForm.machineTypeName = ''
    dataForm.id = ''
    dataForm.customerName = ''
  }

  //按钮权限
  const permissionStore = usePermission()
  if (permissionStore.hasPermisson('zlqjsz.cx')) {
    pageData.btnList.push('查询')
  }
  if (permissionStore.hasPermisson('zlqjsz.xz')) {
    pageData.btnList.push('新增')
  }
  if (permissionStore.hasPermisson('zlqjsz.dr')) {
    pageData.btnList.push('导入')
  }
  // if (permissionStore.hasPermisson('zlqjsz.dc')) {
  //   pageData.btnList.push('下载Excel模板')
  // }
  if (permissionStore.hasPermisson('zlqjsz.sc')) {
    pageData.btnList.push('删除')
  }

  //导出
  const exportHandler = () => {
  //   let selectList = gridOptions.value.getSelectedRows()
  //   // console.log(selectList);
  //   if (selectList.length === 0) {
  //     Message.error('请勾选需要导出的数据')
  //     return
  //   } else {
  //    //将表头拼接出来
  //    let head =
  //           '<th>客户名称</th><th>设备机型</th><th>织单类型</th><th>公斤/匹</th><th>开始重量</th><th>结束重量</th><th>创建人</th><th>创建时间</th>'
  //         //拿到当前表格数据与勾选的行做筛选

  //         // let nowRow = table.dataList.filter(function (o) {
  //         //     return selectedRowKeys.value.indexOf(o["id"]) !== -1;
  //         // })
  //         let nowRow = gridOptions.value.getSelectedRows()
  //         let body = ''
  //         nowRow.forEach(function (o: any) {
  //           body += '<tr><td>' + o['customName'] + '</td>'
  //           body += '<td>' + o['machineTypeName'] + '</td>'
  //           body += '<td>' + o['weaveOrderTypeName'] + '</td>'
  //           body += '<td>' + o['standardCroppingWeight'] + '</td>'
  //           body += '<td>' + o['minWeight'] + '</td>'
  //           body += '<td>' + o['maxWeight'] + '</td>'
  //           body += '<td>' + o['createName'] + '</td>'
  //           body += '<td>' + o['createTime'] + '</td>'
  //           body += '</tr>'
  //         })
  //         tableToXlsx(head, '验后重量限制', body)
  //   }
  // }
  // function tableToXlsx(head: any, filename: any, body: any) {
  //       const uri = 'data:application/vnd.ms-excel;base64,',
  //         template = `<html>
  //           <head><meta charset="UTF-8"></head>
  //           <body><table border="1"><tr>${head}</tr>${body}</table></body>
  //       </html>`

  //       const a = document.createElement('a')
  //       a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
  //       a.download = filename
  //       a.click()
  //       document.removeChild(a)
      }

      //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/wms/GreyStockInWeightLimit/uploadModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          console.log(res);
          
          if (res.status === 200) {
            filedownload(res.data, '重量限制.xlsx')
          }
        })
    }
  //导入
  const importHandler = () => {
    const inputEle: HTMLInputElement = document.createElement('input')
    inputEle.type = 'file'
    inputEle.id = 'fileUploadExcel'
    inputEle.accept =
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
    inputEle.addEventListener('change', (e) => {
      const formData = new FormData()
      if (inputEle.files !== null) {
        formData.append('file', inputEle.files[0] || '')
      } else {
        Message.warning('未选择文件！')
        return
      }
      pageData.pageLoading = true
      axios
        .post(baseURL + '/wms/GreyStockInWeightLimit/importModelData', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((result) => {
          if (result.data['code'] === 200) {
            Message.success('导入成功')
          } else {
            Message.error(result.data.message)
          }
        })
        .finally(() => {
          pageData.pageLoading = false
          doRefresh()
        })
    })
    inputEle.click()
  }
  const selectHander = () => {
    console.log('查询')
    doRefresh()
  }
  //新增按钮
  const addHandler = () => {
    pageData.AddDrawer = true
    disableOr.value = false
    pageData.sideTitle = '新增重量限制表'
    clear()
  }
  const sideOk = () => {
    if (
      dataForm.minWeight == '' ||
      dataForm.maxWeight == '' ||
      dataForm.standardCroppingWeight == ''
    ) {
      Message.warning('请填写完整信息')
      return
    }
    if (Number(dataForm.minWeight) > Number(dataForm.maxWeight)) {
      Message.warning('开始重量不能大于结束重量')
      return
    }

    if (dataForm.id == '' || dataForm.id == undefined) {
      if (
        dataForm.customerName == '' ||
        dataForm.machineTypeName == '' ||
        dataForm.weaveOrderTypeName == ''
      ) {
        Message.warning('请填写完整信息')
        return
      }
      pageData.pageLoading = true
      post({
        url: '/wms/GreyStockInWeightLimit/insert',
        data: {
          minWeight: dataForm.minWeight,
          maxWeight: dataForm.maxWeight,
          standardCroppingWeight: dataForm.standardCroppingWeight,
          weaveOrderTypeName: dataForm.weaveOrderTypeName,
          machineTypeName: dataForm.machineTypeName,
          customName: dataForm.customerName,
        },
      }).then((res: any) => {
        console.log(res)
        if (res.code == 200) {
          pageData.pageLoading = false
          pageData.AddDrawer = false
          clear()

          Message.success({
            content: '添加成功',
            duration: 5000,
          })
          doRefresh()
        } else {
          Message.error(res.msg)
          pageData.pageLoading = false
        }
      })
    } else {
      pageData.pageLoading = true
      post({
        url: '/wms/GreyStockInWeightLimit/update',
        data: {
          id: dataForm.id,
          minWeight: dataForm.minWeight,
          maxWeight: dataForm.maxWeight,
          standardCroppingWeight: dataForm.standardCroppingWeight,
          weaveOrderTypeName: dataForm.weaveOrderTypeName,
          machineTypeName: dataForm.machineTypeName,
        },
      }).then((res: any) => {
        console.log(res)
        if (res.code == 200) {
          pageData.pageLoading = false
          pageData.AddDrawer = false
          clear()
          Message.success({
            content: '修改成功',
            duration: 5000,
          })
          doRefresh()
        } else {
          Message.error(res.msg)
          pageData.pageLoading = false
        }
      })
    }
  }
  //删除
  const deleteHandler = () => {
    if (gridOptions.value.getSelectedRows().length === 0) {
      Message.error('请先勾选')
      return
    }
    Modal.confirm({
      title: '系统提示',
      content: '确认删除选中的数据?',
      onOk() {
        pageData.pageLoading = true
        post({
          url: '/wms/GreyStockInWeightLimit/delete',
          data: gridOptions.value.getSelectedRows().map((o: any) => {
            return o.id
          }),
        })
          .then(({ code, data }: any) => {
            if (code === 200) {
              Message.success({
                content: '删除成功',
                duration: 5000,
              })
              pageData.page = 1
              doRefresh()
            } else {
              Message.error({
                content: '删除失败',
                duration: 5000,
              })
            }
          })
          .finally(() => {
            pageData.pageLoading = false
          })
      },
    })
  }

  const selectAwait = async (
    selectIndex: number,
    value: any = '',
    cb = (data: any) => {
      return data
    }
  ) => {
    post({
      url: 'product/Brand/getList',
      data: { deleteState: 0 },
    }).then((res: any) => {
      if (res.code == 200) {
        console.log(selectIndex)
        console.log(value)
        //查询客户名称
        if (selectIndex == 1) {
          pageData.customerList = res.data
          console.log(res.data)
          if (res.data?.length > 0) {
            res.data.map((o: any) => {
              pageData.customerList.push({ typeName: o.brandName })
            })
          }

          pageData.customerList = Array.from(new Set(pageData.customerList))
        } else {
          //新增查询客户名称
          dataForm.customerList = res.data
          if (res.data?.length > 0) {
            res.data.map((o: any) => {
              dataForm.customerList.push({ typeName: o.brandName })
            })
          }
          dataForm.customerList = Array.from(new Set(dataForm.customerList))
        }
      } else {
        Message.error({ content: '查询失败！', duration: 5000 })
      }
    })
  }

  const gridOptions = ref()
  const colState = ref()
  const gridReady = (params: any) => {
    gridOptions.value = params.api
    colState.value = params.columnApi
  }
  const vehicleColDefs = [
    {
      showRowGroup: 'hide_def',
      headerName: '',
      checkboxSelection: true,
      headerCheckboxSelection: true,
      pinned: 'left',
      width: 50,
      resizable: false,
      filter: false,
      sortable: false,
      minWidth: 50,
      maxWidth: 50,
      lockPosition: 'left',
    },
    {
      headerName: '客户名称',
      field: 'customName',
      width: 200,
    },
    {
      headerName: '设备机型',
      field: 'machineTypeName',
      width: 200,
    },
    {
      headerName: '织单类型',
      field: 'weaveOrderTypeName',
      width: 200,
    },
    {
      headerName: '公斤/匹',
      field: 'standardCroppingWeight',
      width: 200,
    },
    {
      headerName: '开始重量',
      field: 'minWeight',
      width: 200,
    },
    {
      headerName: '结束重量',
      field: 'maxWeight',
      width: 200,
    },
    {
      headerName: '创建人',
      field: 'createName',
      width: 200,
    },
    {
      headerName: '创建时间',
      field: 'createTime',
      width: 204,
    },
    {
      headerName: '操作',
      field: 'option',
      width: 204,
      cellRenderer: {
        template: `
              <a-space>
                          <a-button v-if="e" type="primary" size="mini" status="warning" @click="a1">
                              <template #icon>
                                  <icon-edit />
                              </template>
                              修 改
                          </a-button>
                              </a-space>
              `,
        setup(props: any) {
          const option = ref(props.params.data)
          const a1 = () => {
            editHandler(props.params.data)
          }

          return {
            a1,
            option,
            e: permissionStore.hasPermisson('zlqjsz.xg'),
          }
        },
      },
    },
  ]

  //修改
  let disableOr = ref(false)
  const editHandler = (data: any) => {
    console.log(data)

    pageData.AddDrawer = true
    //不可修改
    disableOr.value = true
    nextTick(() => {
      pageData.sideTitle = '修改重量限制'
      console.log(data)
      dataForm.minWeight = data.minWeight
      dataForm.maxWeight = data.maxWeight
      dataForm.standardCroppingWeight = data.standardCroppingWeight
      dataForm.customerName = data.customName
      dataForm.id = data.id
      dataForm.weaveOrderTypeName = data.weaveOrderTypeName
      dataForm.machineTypeName = data.machineTypeName
    })
  }
  const tableDataList = ref([])

  const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
    saveOrUpdateGridState01('VehicleRecords-1', gridOptions, colState, vehicleColDefs)
  const onColumnMoved = () => {
    saveGridState01()
  }
  const onColumnResized = () => {
    saveGridState01()
  }
  const onColumnVisible = () => {
    saveGridState01()
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
  }
  const PageSize = (val: any) => {
    console.log(val)

    pageData.page = val
    doRefresh()
  }
  function change1(val: any) {
    console.log(val)

    pageData.size = val
    doRefresh()
  }
  const table = useTable()

  const doRefresh = () => {
    console.log(pageData)
    pageData.pageLoading = true
    updateGridState01()
    post({
      url: '/wms/GreyStockInWeightLimit/getPage',
      data: {
        page: pageData.page,
        size: pageData.size,
        customName: pageData.customerName,
        machineTypeName: pageData.machineTypeName,
        beginTime: pageData.beginTime,
        endTime: pageData.endTime,
      },
    })
      .then(({ data, code }: any) => {
        if (code === 200) {
          tableDataList.value = data.list
          gridOptions.value.setRowData(data.list)

          table.handleSuccess(data.list)
          pageData.total = data.total
        }
      })
      .catch(console.log)
      .finally(() => {
        pageData.pageLoading = false
      })
  }

  onMounted(() => {
    doRefresh()
  })
</script>
<script lang="ts">
  export default {
    name: 'StoreBasicInformation',
  }
</script>
<style scoped lang="less"></style>
